#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2022/6/2 14:03
# @Author    :cjw
import os

from appium import webdriver

from app_wework.base.base_page import BasePage
from app_wework.page.main_page import MainPage
from app_wework.setting import DES_CAPS
from app_wework.util.file_operator import YmlOperator
from app_wework.util.log import logger
from app_wework.setting import IMPLICITLY_WAIT_TIMEOUT, COMMAND_EXECUTOR_IP


class BaseApp(BasePage):
	"""app相关操作：启动、关闭、重启"""

	def start(self):
		"""启动app"""
		if not self.driver:
			logger.info('开始初始化操作，创建driver，建立session会话')
			des_caps = YmlOperator(DES_CAPS).data  # 获取启动参数
			device_name = os.getenv('device')  # 获取设备名称
			port = os.getenv('port')  # 获取服务启动端口

			# 设备和启动端口判断
			caps = {}
			if device_name:
				device_name = device_name.lower()
				if device_name == 'p20':
					caps = des_caps.get('huawei_p20')
			else:
				caps = des_caps.get('simulator_ys')
			port = port if port else '4723'

			# 启动app
			try:
				self.driver = webdriver.Remote(f'{COMMAND_EXECUTOR_IP}:{port}/wd/hub', caps)
				self.driver.implicitly_wait(IMPLICITLY_WAIT_TIMEOUT)
			except Exception as ex:
				logger.error(f'启动app失败，报错信息：{ex}')
				raise ex
		else:
			"""
			launch_app(): 本机启动driver中app
			start_activity：指定app_package和app_activity本机启动app
			"""
			logger.info('复用driver, 启动app')
			self.driver.launch_app()

		return self

	def restart(self):
		"""重启app"""
		logger.info("重启app。。。")
		self.driver.close_app()
		self.driver.launch_app()

	def close_app_back(self, num: int = 5):
		"""
		通过back操作，关闭app
		:param num: 按back的次数，默认5次
		:return:
		"""
		logger.info('通过back操作，关闭app')
		for i in range(num):
			self.driver.back()

	def close_app(self):
		"""关闭app"""
		logger.info('关闭app')
		self.driver.close_app()

	def quit(self):
		"""关闭session"""
		logger.info('关闭创建的session会话')
		self.driver.quit()

	def goto_main(self):
		"""进入app的主页"""
		return MainPage(self.driver)
